<template>
  <div class="template-preview">
    <div class="preview-header">
      <div class="template-info">
        <h3>{{ templateData.name }}</h3>
        <div class="template-meta">
          <el-tag :type="getDepartmentTagType(templateData.department)" size="small">
            {{ getDepartmentText(templateData.department) }}
          </el-tag>
          <el-tag :type="getTypeTagType(templateData.type)" size="small">
            {{ getTypeText(templateData.type) }}
          </el-tag>
          <el-tag v-if="templateData.isDefault" type="success" size="small">
            默认模板
          </el-tag>
        </div>
        <p class="template-description">{{ templateData.description }}</p>
      </div>
      <div class="preview-actions">
        <el-button type="primary" @click="handleUseTemplate">
          <el-icon><Check /></el-icon>
          使用此模板
        </el-button>
        <el-button @click="handleClose">
          <el-icon><Close /></el-icon>
          关闭
        </el-button>
      </div>
    </div>

    <div class="preview-content">
      <!-- 模板内容预览 -->
      <div class="preview-document">
        <!-- 病历头信息 -->
        <div class="document-header">
          <div class="hospital-info">
            <h2>智医云联医院</h2>
            <p>电子病历</p>
          </div>
          <div class="patient-info">
            <div class="info-grid">
              <div class="info-item">
                <label>患者姓名：</label>
                <span class="variable">[{{ patientInfo.name }}]</span>
              </div>
              <div class="info-item">
                <label>性别：</label>
                <span class="variable">[{{ patientInfo.gender }}]</span>
              </div>
              <div class="info-item">
                <label>年龄：</label>
                <span class="variable">[{{ patientInfo.age }}]</span>
              </div>
              <div class="info-item">
                <label>就诊时间：</label>
                <span class="variable">[{{ currentTime }}]</span>
              </div>
              <div class="info-item">
                <label>科室：</label>
                <span class="variable">[{{ departmentInfo.name }}]</span>
              </div>
              <div class="info-item">
                <label>医生：</label>
                <span class="variable">[{{ doctorInfo.name }}]</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 模板内容各章节 -->
        <div class="document-sections">
          <!-- 主诉 -->
          <section v-if="templateData.content.chiefComplaint" class="document-section">
            <h4 class="section-title">主诉</h4>
            <div class="section-content formatted-text">
              {{ formatTemplateText(templateData.content.chiefComplaint) }}
            </div>
          </section>

          <!-- 现病史 -->
          <section v-if="templateData.content.presentIllness" class="document-section">
            <h4 class="section-title">现病史</h4>
            <div class="section-content formatted-text">
              {{ formatTemplateText(templateData.content.presentIllness) }}
            </div>
          </section>

          <!-- 既往史 -->
          <section v-if="templateData.content.pastHistory" class="document-section">
            <h4 class="section-title">既往史</h4>
            <div class="section-content formatted-text">
              {{ formatTemplateText(templateData.content.pastHistory) }}
            </div>
          </section>

          <!-- 过敏史 -->
          <section v-if="templateData.content.allergyHistory" class="document-section">
            <h4 class="section-title">过敏史</h4>
            <div class="section-content formatted-text">
              {{ formatTemplateText(templateData.content.allergyHistory) }}
            </div>
          </section>

          <!-- 体格检查 -->
          <section v-if="templateData.content.physicalExam" class="document-section">
            <h4 class="section-title">体格检查</h4>
            <div class="section-content formatted-text">
              {{ formatTemplateText(templateData.content.physicalExam) }}
            </div>
          </section>

          <!-- 辅助检查 -->
          <section v-if="templateData.content.labResults" class="document-section">
            <h4 class="section-title">辅助检查</h4>
            <div class="section-content formatted-text">
              {{ formatTemplateText(templateData.content.labResults) }}
            </div>
          </section>

          <!-- 诊断 -->
          <section v-if="templateData.content.diagnosis" class="document-section">
            <h4 class="section-title">诊断</h4>
            <div class="section-content formatted-text">
              {{ formatTemplateText(templateData.content.diagnosis) }}
            </div>
          </section>

          <!-- 治疗方案 -->
          <section v-if="templateData.content.treatmentPlan" class="document-section">
            <h4 class="section-title">治疗方案</h4>
            <div class="section-content formatted-text">
              {{ formatTemplateText(templateData.content.treatmentPlan) }}
            </div>
          </section>

          <!-- 医嘱 -->
          <section v-if="templateData.content.medicalAdvice" class="document-section">
            <h4 class="section-title">医嘱</h4>
            <div class="section-content formatted-text">
              {{ formatTemplateText(templateData.content.medicalAdvice) }}
            </div>
          </section>
        </div>

        <!-- 医生签名区域 -->
        <div class="document-footer">
          <div class="signature-area">
            <div class="doctor-signature">
              <div class="signature-line"></div>
              <div class="signature-info">
                <span class="variable">[{{ doctorInfo.name }}]</span>
                <span>医师签名</span>
              </div>
            </div>
            <div class="record-time">
              <span>记录时间：</span>
              <span class="variable">[{{ currentTime }}]</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 模板使用统计 -->
      <el-card class="usage-stats-card">
        <template #header>
          <div class="card-header">
            <span>模板使用统计</span>
          </div>
        </template>
        <div class="stats-content">
          <div class="stat-item">
            <div class="stat-value">{{ templateData.usageCount || 0 }}</div>
            <div class="stat-label">使用次数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ templateData.updateTime ? formatDate(templateData.updateTime) : '-' }}</div>
            <div class="stat-label">最后更新</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ getDepartmentText(templateData.department) }}</div>
            <div class="stat-label">适用科室</div>
          </div>
        </div>
      </el-card>

      <!-- 变量说明 -->
      <el-card class="variables-card">
        <template #header>
          <div class="card-header">
            <span>模板变量说明</span>
          </div>
        </template>
        <div class="variables-list">
          <div class="variable-item" v-for="variable in usedVariables" :key="variable.name">
            <div class="variable-name">
              <code>{{ variable.variable }}</code>
            </div>
            <div class="variable-desc">{{ variable.description }}</div>
            <div class="variable-preview">
              <el-tag size="small" type="info">{{ variable.preview }}</el-tag>
            </div>
          </div>
          <div v-if="usedVariables.length === 0" class="no-variables">
            <el-empty description="本模板未使用变量" :image-size="80" />
          </div>
        </div>
      </el-card>
    </div>

    <!-- 使用模板对话框 -->
    <el-dialog
      v-model="useDialogVisible"
      title="使用模板"
      width="500px"
    >
      <div class="use-template-dialog">
        <el-form :model="useForm" label-width="80px">
          <el-form-item label="选择患者">
            <el-select
              v-model="useForm.patientId"
              placeholder="请选择患者"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="patient in patientList"
                :key="patient.id"
                :label="`${patient.name} (${patient.age}岁, ${patient.gender})`"
                :value="patient.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="就诊类型">
            <el-radio-group v-model="useForm.visitType">
              <el-radio label="initial">初诊</el-radio>
              <el-radio label="followup">复诊</el-radio>
              <el-radio label="emergency">急诊</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="useForm.remark"
              type="textarea"
              :rows="3"
              placeholder="可输入额外备注信息"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="useDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUseTemplate" :loading="usingTemplate">
          确认使用
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Check, Close } from '@element-plus/icons-vue'

const props = defineProps({
  templateData: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['use-template', 'close'])

// 响应式数据
const useDialogVisible = ref(false)
const usingTemplate = ref(false)

// 使用表单
const useForm = reactive({
  patientId: null,
  visitType: 'initial',
  remark: ''
})

// 模拟数据
const patientInfo = reactive({
  name: '张三',
  gender: '男',
  age: '35岁'
})

const doctorInfo = reactive({
  name: '张医生'
})

const departmentInfo = reactive({
  name: '内科'
})

const currentTime = ref('2024-03-20 14:30:00')

const patientList = ref([
  { id: 1, name: '李永豪', age: 35, gender: '男' },
  { id: 2, name: '王瑞霞', age: 42, gender: '女' },
  { id: 3, name: '张琳', age: 29, gender: '女' },
  { id: 4, name: '王晓辉', age: 58, gender: '男' }
])

// 可用变量定义
const availableVariables = ref([
  { variable: 'patient.name', name: '患者姓名', description: '患者全名', preview: '张三' },
  { variable: 'patient.age', name: '患者年龄', description: '患者当前年龄', preview: '35岁' },
  { variable: 'patient.gender', name: '患者性别', description: '患者性别', preview: '男' },
  { variable: 'patient.phone', name: '患者电话', description: '患者联系电话', preview: '138****1234' },
  { variable: 'patient.idCard', name: '身份证号', description: '患者身份证号码', preview: '110101198901011234' },
  { variable: 'current.date', name: '当前日期', description: '系统当前日期', preview: '2024-03-20' },
  { variable: 'current.time', name: '当前时间', description: '系统当前时间', preview: '14:30:00' },
  { variable: 'doctor.name', name: '医生姓名', description: '当前医生姓名', preview: '张医生' },
  { variable: 'department.name', name: '科室名称', description: '当前科室名称', preview: '内科' },
  { variable: 'hospital.name', name: '医院名称', description: '医院全称', preview: '智医云联医院' }
])

// 计算属性
const usedVariables = computed(() => {
  const variables = new Set()
  const content = props.templateData.content
  
  // 检查模板内容中使用的变量
  Object.values(content).forEach(text => {
    if (text) {
      const matches = text.match(/{{(.*?)}}/g) || []
      matches.forEach(match => {
        const variableName = match.replace(/{{|}}/g, '')
        const variableInfo = availableVariables.value.find(v => v.variable === variableName)
        if (variableInfo) {
          variables.add(variableInfo)
        }
      })
    }
  })
  
  return Array.from(variables)
})

const hasContent = computed(() => {
  return Object.values(props.templateData.content).some(value => value && value.trim() !== '')
})

// 方法
const formatTemplateText = (text) => {
  if (!text) return ''
  
  // 替换变量为示例值
  return text
    .replace(/{{patient\.name}}/g, '张三')
    .replace(/{{patient\.age}}/g, '35岁')
    .replace(/{{patient\.gender}}/g, '男')
    .replace(/{{patient\.phone}}/g, '138****1234')
    .replace(/{{patient\.idCard}}/g, '110101198901011234')
    .replace(/{{current\.date}}/g, '2024-03-20')
    .replace(/{{current\.time}}/g, '14:30:00')
    .replace(/{{doctor\.name}}/g, '张医生')
    .replace(/{{department\.name}}/g, '内科')
    .replace(/{{hospital\.name}}/g, '智医云联医院')
}

const getDepartmentText = (department) => {
  const departmentMap = {
    internal: '内科',
    surgery: '外科',
    pediatrics: '儿科',
    obstetrics: '妇产科',
    ophthalmology: '眼科',
    ent: '耳鼻喉科',
    dermatology: '皮肤科',
    tcm: '中医科'
  }
  return departmentMap[department] || department
}

const getDepartmentTagType = (department) => {
  const typeMap = {
    internal: 'primary',
    surgery: 'success',
    pediatrics: 'warning',
    obstetrics: 'danger',
    ophthalmology: 'info',
    ent: 'primary',
    dermatology: 'success',
    tcm: 'warning'
  }
  return typeMap[department] || 'info'
}

const getTypeText = (type) => {
  const typeMap = {
    initial: '初诊病历',
    followup: '复诊病历',
    emergency: '急诊病历',
    inpatient: '住院病历',
    physical: '体检病历'
  }
  return typeMap[type] || type
}

const getTypeTagType = (type) => {
  const typeMap = {
    initial: 'primary',
    followup: 'success',
    emergency: 'warning',
    inpatient: 'danger',
    physical: 'info'
  }
  return typeMap[type] || 'info'
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return dateString.split(' ')[0]
}

const handleUseTemplate = () => {
  useDialogVisible.value = true
}

const handleClose = () => {
  emit('close')
}

const confirmUseTemplate = async () => {
  if (!useForm.patientId) {
    ElMessage.warning('请选择患者')
    return
  }

  usingTemplate.value = true
  try {
    // TODO: 调用API使用模板创建病历
    // await medicalRecordApi.createFromTemplate({
    //   templateId: props.templateData.id,
    //   patientId: useForm.patientId,
    //   visitType: useForm.visitType,
    //   remark: useForm.remark
    // })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const selectedPatient = patientList.value.find(p => p.id === useForm.patientId)
    ElMessage.success(`已为患者 ${selectedPatient.name} 创建病历`)
    
    useDialogVisible.value = false
    emit('use-template', props.templateData)
  } catch (error) {
    ElMessage.error('使用模板失败')
  } finally {
    usingTemplate.value = false
  }
}

// 初始化当前时间
onMounted(() => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
})
</script>

<style lang="scss" scoped>
.template-preview {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px;
  background: white;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.template-info {
  flex: 1;
  
  h3 {
    margin: 0 0 12px 0;
    color: #303133;
    font-size: 20px;
  }
}

.template-meta {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.template-description {
  margin: 0;
  color: #606266;
  line-height: 1.5;
}

.preview-actions {
  display: flex;
  gap: 12px;
}

.preview-content {
  flex: 1;
  padding: 0 20px 20px;
  overflow-y: auto;
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  align-items: start;
}

.preview-document {
  background: white;
  border: 1px solid #e1e4e8;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-height: 800px;
}

.document-header {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #409eff;
}

.hospital-info {
  text-align: center;
  margin-bottom: 20px;
  
  h2 {
    margin: 0 0 8px 0;
    color: #1a75bc;
    font-size: 24px;
  }
  
  p {
    margin: 0;
    color: #606266;
    font-size: 16px;
  }
}

.patient-info {
  .info-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    
    .info-item {
      display: flex;
      align-items: center;
      
      label {
        font-weight: 500;
        color: #606266;
        min-width: 80px;
        margin-right: 8px;
      }
      
      .variable {
        color: #409eff;
        font-weight: 500;
        background: #f0f7ff;
        padding: 2px 6px;
        border-radius: 3px;
        border: 1px dashed #409eff;
      }
    }
  }
}

.document-sections {
  .document-section {
    margin-bottom: 24px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.section-title {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  padding-bottom: 6px;
  border-bottom: 1px solid #f0f0f0;
}

.section-content {
  color: #303133;
  line-height: 1.8;
  white-space: pre-wrap;
}

.formatted-text {
  font-size: 14px;
  text-indent: 2em;
}

.document-footer {
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #e1e4e8;
}

.signature-area {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.doctor-signature {
  .signature-line {
    width: 200px;
    height: 1px;
    background: #303133;
    margin-bottom: 4px;
  }
  
  .signature-info {
    display: flex;
    gap: 20px;
    font-size: 14px;
    color: #606266;
    
    .variable {
      color: #409eff;
      font-weight: 500;
    }
  }
}

.record-time {
  font-size: 14px;
  color: #606266;
  
  .variable {
    color: #409eff;
    font-weight: 500;
  }
}

.usage-stats-card,
.variables-card {
  margin-bottom: 20px;
}

.stats-content {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  text-align: center;
}

.stat-item {
  .stat-value {
    font-size: 20px;
    font-weight: 600;
    color: #409eff;
    margin-bottom: 4px;
  }
  
  .stat-label {
    font-size: 12px;
    color: #909399;
  }
}

.variables-list {
  .variable-item {
    display: flex;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .variable-name {
      flex: 0 0 150px;
      
      code {
        background: #f5f7fa;
        padding: 2px 6px;
        border-radius: 3px;
        font-family: 'Monaco', 'Menlo', monospace;
        font-size: 12px;
        color: #e96900;
      }
    }
    
    .variable-desc {
      flex: 1;
      color: #606266;
      font-size: 13px;
      padding: 0 12px;
    }
    
    .variable-preview {
      flex: 0 0 100px;
      text-align: right;
    }
  }
}

.no-variables {
  padding: 20px 0;
}

.use-template-dialog {
  .el-form-item {
    margin-bottom: 20px;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .preview-content {
    grid-template-columns: 1fr;
  }
  
  .patient-info .info-grid {
    grid-template-columns: 1fr 1fr;
  }
}

@media (max-width: 768px) {
  .preview-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .preview-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .patient-info .info-grid {
    grid-template-columns: 1fr;
  }
  
  .stats-content {
    grid-template-columns: 1fr;
  }
  
  .variables-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    
    .variable-desc {
      padding: 0;
    }
    
    .variable-preview {
      text-align: left;
    }
  }
}
</style>